package com.pro01.backend.mapper;

import com.pro01.backend.pojo.LotteryLog;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

@Mapper
public interface LotteryLogMapper {

    // 插入一条抽奖记录
    @Insert("""
        INSERT INTO lottery_logs (user_id, prize_name, prize_type, prize_value, created_at)
        VALUES (#{userId}, #{prizeName}, #{prizeType}, #{prizeValue}, NOW())
    """)
    int insertLotteryLog(LotteryLog log);

    // 用户分页查询自己的抽奖记录
    @Select("""
        SELECT * FROM lottery_logs
        WHERE user_id = #{userId}
        ORDER BY created_at DESC
        LIMIT #{offset}, #{pageSize}
    """)
    List<LotteryLog> getLogsByUser(@Param("userId") Long userId,
                                   @Param("offset") int offset,
                                   @Param("pageSize") int pageSize);

    // 查询用户抽奖记录总数
    @Select("SELECT COUNT(*) FROM lottery_logs WHERE user_id = #{userId}")
    int countLogsByUser(@Param("userId") Long userId);

    /**
     * 下面是管理员接口
     */

    // 管理员查看抽奖记录
    @Select("""
    SELECT l.*, u.username
    FROM lottery_logs l
    LEFT JOIN users u ON l.user_id = u.id
    ORDER BY l.created_at DESC
    LIMIT #{offset}, #{pageSize}
""")
    List<Map<String, Object>> getAllLogsPaged(@Param("offset") int offset,
                                              @Param("pageSize") int pageSize);

    @Select("SELECT COUNT(*) FROM lottery_logs")
    int countAllLogs();

    // 管理员查看抽奖结果统计
    @Select("""
    SELECT prize_name, prize_type, prize_value, COUNT(*) AS count
    FROM lottery_logs
    GROUP BY prize_name, prize_type, prize_value
    ORDER BY count DESC
""")
    List<Map<String, Object>> getPrizeStats();

    @Select("SELECT COUNT(*) FROM lottery_logs")
    int countTotalDraws();

}
